
import define as df
import train
import os
import json
import pandas as pd



def run_turi(code, json_val):
    cmd = 'turi {model} \'{json}\''.format(model=code, json=json_val)
    print(cmd)
    cmd_result = os.popen(cmd)
    text = cmd_result.read()
    if text.startswith('{'):
        dict = json.loads(text)
        return dict
    return None

def generate_current(code):
    res = train.fetch_recent([code])
    if res == None:
        print('[generate_current] can not fetch from web')
        return None

    his = fetch_last_history(code)
    if his == None:
        print('[generate_current] can not fetch from history')
        return None

    val = float(res[code]['current'])

    gen = train.ready_gen_single(his, val)
    json_param = gen.iloc[0].to_json()
    cmd = run_turi(code, json_param)
    if cmd == None:
        return None
    else:
        if dict['Code'] != 0:
            print('error cmd:{dict}'.format(dict=dict))
            return None
        else:
            dict['Code'] = code
            dict['Info'] = res[code]
            dict['History'] = json_param
            return dict


def generate_last(code):
    his = fetch_last_history(code)
    if his == None:
        print('[generate_last] can not fetch last history')
        return None

    gen = train.ready_gen(his)
    json_param = gen.iloc[0].to_json()
    print(json_param)
    cmd = run_turi(code, json_param)
    if cmd == None:
        return None
    else:
        if dict['Code'] != 0:
            print('error cmd:{dict}'.format(dict=dict))
            return None
        else:
            dict['Code'] = code
            dict['History'] = json_param
            return dict

